package com.zbmsg.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.zbmsg.consts.BaseController;
import com.zbmsg.group.bean.Group;
import com.zbmsg.group.service.IGroupService;
import com.zbmsg.user.bean.User;
import com.zbmsg.user.service.IUserService;
import com.zbmsg.utils.common.Response;

@RestController
@RequestMapping("group")
public class GroupController extends BaseController {

	@Autowired
	private IGroupService groupService;
	@Autowired
	private IUserService userService;

	@RequestMapping(value = "check", produces = "application/json; charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public String checkUserIsCreateGroup(HttpServletRequest request) {
		String userId = getUserId(request);
		HashMap<String, Object> reultMap = null;
		try {
			Group group = this.groupService.isCreateGroup(userId);
			if (group == null) {
				return Response.result(Response.OPERATION_NULL, "", "");
			}
			reultMap = new HashMap<>();
			reultMap.put("groupId", group.getGroupId());
		} catch (Exception e) {
			e.getMessage();
		}
		return Response.ok(reultMap);
	}

	@RequestMapping(value = "create", produces = "application/json; charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public String createGroup(HttpServletRequest request,
			@RequestParam(value = "groupName", required = true) String groupName) {
		String userId = getUserId(request);
		HashMap<String, Object> reultMap = null;
		try {
			reultMap = new HashMap<>();
			Group group = new Group();
			group.setGroupName(groupName);
			group.setUserId(userId);
			String groupId = this.groupService.add(group);
			reultMap.put("groupId", groupId);
		} catch (Exception e) {
			e.getMessage();
		}
		return Response.ok(reultMap);
	}

	@RequestMapping(value = "list", produces = "application/json; charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public String listWithGroups() {
		List<Map<String, Object>> reultList = new ArrayList<>();
		try {
			List<Group> groups = this.groupService.listWithGroups();
			for (Group group : groups) {
				Map<String, Object> map = new HashMap<>();
				User user = this.userService.getUserByUserId(group.getUserId());
				map.put("groupId", group.getGroupId());
				map.put("groupName", group.getGroupName());
				map.put("userName", user.getName());
				reultList.add(map);
			}
		} catch (Exception e) {
			e.getMessage();
		}
		return Response.ok(reultList);
	}

}
